	//
	//  JsInputBox.m
	//  DuTe
	//
	//  Created by Gikki Ares on 2020/12/22.
	//  Copyright © 2020 vgemv. All rights reserved.
	//

#import "JsInputBox.h"
#import <JsUtilitySdk/JsUtilitySdk.h>
#import "AGEmojiKeyBoardView.h"
#import "JsVoiceInputView.h"


@interface JsInputBox()<
JsButtonLiiTwoDelegate,
UITextViewDelegate,
AGEmojiKeyboardViewDelegate,
AGEmojiKeyboardViewDataSource,
JsVoiceInputViewDelegate,
JsButtonLiiOneDelegate
>

{
	JsInputBoxVm * mvm;
	UITextView * mtv;
	UILabel * mlb_palceHolder;
	JsButtonLiiTwo * mJsButtonLii_expression;
	JsButtonLiiTwo * mJsButtonLii_voice;
	JsButtonLiiOne * mJsButtonLii_publish;
	
	
	bool mb_isChangeKeyboard;
}

@end

const static int ViewTag_Expression = 1;
const static int ViewTag_Voice = 2;
const static int ViewTag_Publish = 3;

@implementation JsInputBox

- (instancetype)init {
	if(self =[super init]) {
		[self commonInit];
	}
	return self;
}

- (void)commonInit {
	mvm = [JsInputBoxVm defaultInstance];
	mtv = [UITextView new];
	mtv.delegate = self;
	mtv.backgroundColor = [UIColor grayColorWithWhite:247];
	mtv.layer.cornerRadius = 5;
	mtv.layer.masksToBounds = YES;
	mtv.textColor = mvm.mcolor_text;
	
	mlb_palceHolder = [UILabel new];
	mlb_palceHolder.text = mvm.mstr_placeHolder;
	mlb_palceHolder.textColor = mvm.mcolor_placeHolder;
	mlb_palceHolder.font = mvm.mfont_text;
	mtv.font = mvm.mfont_text;
	
	UIImage * image_keyboard = [JsBundleManager iconInBundleNamed:@"Keybord_Black.png"];
		//创建这些按钮时,要保证大小的正确性.这样这些控件内部的布局将不用再改变.
	{
		mJsButtonLii_expression = [[JsButtonLiiTwo alloc]initWithFrame:[mvm expressBtnFrame]];
		
		
		UIImage * image_expression = [JsBundleManager iconInBundleNamed:@"Expression_Black.png"];
		JsButtonLiiVm * vm_unselected = [mJsButtonLii_expression unselectedVm];
		vm_unselected.foregroundImageViewFrame = [JsGeometryManager frameAlignCenterWithContainerSize:[mvm expressBtnFrame].size size:CGSizeMake(26, 26)];
		
		JsButtonLiiVm * vm_selected = [mJsButtonLii_expression selectedVm];
		
		vm_selected.foregroundImageViewFrame = [JsGeometryManager frameAlignCenterWithContainerSize:[mvm expressBtnFrame].size size:CGSizeMake(26, 26)];
		
		[mJsButtonLii_expression setSelectedImage:image_keyboard unselectedImage:image_expression];
		[mJsButtonLii_expression setupUi];
		mJsButtonLii_expression.delegate = self;
		mJsButtonLii_expression.tag = ViewTag_Expression;
	}
	
	{
		mJsButtonLii_voice = [[JsButtonLiiTwo alloc]initWithFrame:[mvm voiceBtnFrame]];
			//	JsButtonLiiVm * vm_voice = [mJsButtonLii_voice vm];
		UIImage * image_microphone = [JsBundleManager iconInBundleNamed:@"Microphone_Black.png"];
		[mJsButtonLii_voice setSelectedImage:image_keyboard unselectedImage:image_microphone];
		
		JsButtonLiiVm * vm_unselected = [mJsButtonLii_voice unselectedVm];
		vm_unselected.foregroundImageViewFrame = [JsGeometryManager frameAlignCenterWithContainerSize:[mvm expressBtnFrame].size size:CGSizeMake(26, 26)];
		JsButtonLiiVm * vm_selected = [mJsButtonLii_voice selectedVm];
		vm_selected.foregroundImageViewFrame = [JsGeometryManager frameAlignCenterWithContainerSize:[mvm expressBtnFrame].size size:CGSizeMake(26, 26)];
		
		[mJsButtonLii_voice setupUi];
		mJsButtonLii_voice.delegate = self;
		mJsButtonLii_voice.tag =ViewTag_Voice;
	}
	
		//发布按钮
	mJsButtonLii_publish = [[JsButtonLiiOne alloc]initWithFrame:[mvm publishBtnFrame]];
	mJsButtonLii_publish.delegate = self;
	JsButtonLiiVm * vm_publish = [mJsButtonLii_publish vm];
	[mJsButtonLii_publish setTitle:@"发布"];
	mJsButtonLii_publish.tag = ViewTag_Publish;
	
	vm_publish.labelFont = [UIFont systemFontOfSize:16];
	mJsButtonLii_publish.layer.borderWidth = 1;
	mJsButtonLii_publish.layer.cornerRadius = 3;
	
	mJsButtonLii_publish.layer.masksToBounds = YES;
	[mJsButtonLii_publish setupUi];
	
	[self addSubview:mtv];
	[self addSubview:mJsButtonLii_expression];
	[self addSubview:mJsButtonLii_voice];
	[self addSubview:mJsButtonLii_publish];
	[self addSubview:mlb_palceHolder];
	
		//监听键盘弹出的代理
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}


#pragma mark 3  Interface
- (JsInputBoxVm *)vm {
	return mvm;
}

- (NSString *)getText {
	return mtv.text;
}

- (void)setPlaceholder:(NSString *)placeholder {
	mvm.mstr_placeHolder = placeholder;
	[self updateUi];
}


- (void)updateUi {
	[mvm doCaculate];
	self.frame = [mvm frame];
	mtv.frame = [mvm textViewFrame];
//	mtv.text = mvm.mstr_text;
	mJsButtonLii_expression.frame = [mvm expressBtnFrame];
	mJsButtonLii_voice.frame = [mvm voiceBtnFrame];
	mJsButtonLii_publish.frame = [mvm publishBtnFrame];
	self.backgroundColor = [UIColor whiteColor];
	
	if(!mvm.mstr_text.length) {
			//内容为空
		CGRect textFrame = [mvm placeholdLabelFrame];
		mlb_palceHolder.frame = textFrame;
		mlb_palceHolder.text = mvm.mstr_placeHolder;
		mlb_palceHolder.hidden = NO;
		[mJsButtonLii_publish updateFontColor:mvm.mcolor_publish_textEmpty];
		mJsButtonLii_publish.layer.borderColor = mvm.mcolor_publish_textEmpty.CGColor;
	}
	else {
			//内容不为空
		mlb_palceHolder.hidden = YES;
		[mJsButtonLii_publish updateFontColor:mvm.mcolor_publish_textNotEmpty];
		mJsButtonLii_publish.layer.borderColor = mvm.mcolor_publish_textNotEmpty.CGColor;
	}
}

/**
 layoutSubViews发生的时机,是在runloop中,用户处理之后,有一定的滞后.
 */
- (void)layoutSubviews {
	[super layoutSubviews];
	[self updateUi];
}

- (void)becomeFirstResponder {
	[mtv becomeFirstResponder];
}


#pragma mark 4 Delegate
	//先选中,再调用回调.
-(void)jsButtonLiiTwoClicked:(JsButtonLiiTwo *)button {
	switch (button.tag) {
		case ViewTag_Expression:{
			mb_isChangeKeyboard = YES;
			if([button isSelected]) {
					//显示emoji输入
				AGEmojiKeyboardView *emojiKeyboardView = [[AGEmojiKeyboardView alloc] initWithFrame:CGRectMake(0, 0,mvm.mf_width, 216) dataSource:self];
				emojiKeyboardView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
				emojiKeyboardView.delegate = self;
				mtv.inputView = emojiKeyboardView;
				
				[mtv resignFirstResponder];
				
				dispatch_async(dispatch_get_main_queue(), ^{
					[self->mtv becomeFirstResponder];
				});
				
				if([mJsButtonLii_voice isSelected]) {
					[mJsButtonLii_voice toggle];
				}
				
			}
			else {
					//显示系统键盘
				mtv.inputView = nil;
				[mtv resignFirstResponder];
				
				dispatch_async(dispatch_get_main_queue(), ^{
					[self->mtv becomeFirstResponder];
				});
				
			}
			break;
		}
		case ViewTag_Voice:{
			mb_isChangeKeyboard = YES;
			if([button isSelected]) {
					//显示emoji输入
				JsVoiceInputView *jsVoiceInputView = [[JsVoiceInputView alloc] initWithFrame:CGRectMake(0, 0,mvm.mf_width, 200)];
				mtv.inputView = jsVoiceInputView;
				jsVoiceInputView.delegate = self;
				[mtv resignFirstResponder];
				
				dispatch_async(dispatch_get_main_queue(), ^{
					[self->mtv becomeFirstResponder];
				});
				
				if([mJsButtonLii_expression isSelected]) {
					[mJsButtonLii_expression toggle];
				}
				
			}
			else {
					//显示系统键盘
				mtv.inputView = nil;
				[mtv resignFirstResponder];
				
				dispatch_async(dispatch_get_main_queue(), ^{
					[self->mtv becomeFirstResponder];
				});
				
			}
			break;
		}
		default:{
			
			break;
		}
	}
}

- (void)jsButtonLiiOneClicked:(JsButtonLiiOne *)button {
	switch(button.tag) {
		case ViewTag_Publish: {
				//点击发布按钮
			if(mtv.text&&mtv.text.length > 0) {
				if(_delegate && [_delegate respondsToSelector:@selector(jsInputBox:publishContent:)]) {
					[_delegate jsInputBox:self publishContent:mtv.text];
				}
			}
		}
	}
}

- (void)onKeyboardShow:(NSNotification *)notification {
		//	NSLog(@"show!!!");
	mb_isChangeKeyboard = NO;
	mvm.mb_isRised = YES;
	if(!mvm.mb_isRising) {
		mvm.mb_isRising = YES;
			//		CGFloat animationTime = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
		CGRect keyboardFrame = [notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
		CGFloat keyboardHeight = keyboardFrame.size.height;
//		NSLog(@"KeyboardHeight is %.2f",keyboardHeight);
		mvm.mf_keyboardHeight = keyboardHeight;
		CGFloat animationTime = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
		
		
		
			//		[CATransaction begin];
			//		[CATransaction setDisableActions:YES];
			//
			//		[CATransaction commit];
		
			//		[UIView setAnimationsEnabled:NO];
		[UIView animateWithDuration:animationTime animations:^{
			self.frame = self->mvm.riseFrame;
		}];
		
			//		[UIView setAnimationsEnabled:YES];
		
		
		
		mvm.mb_isRising = FALSE;
		
	}
}
	//在show之后,为什么会调用hide??
- (void)onKeyboardHide:(NSNotification *)notification {
	if(mb_isChangeKeyboard) {
		return;
	}
	mvm.mb_isRised = FALSE;
		//	NSLog(@"hide!!!");
	if(!mvm.mb_isDowning) {
		mvm.mb_isDowning = YES;
		self.frame = self->mvm.downFrame;
		mvm.mb_isDowning = FALSE;
	}
}

#pragma mark AGEmojiKeyboardViewDelegate AGEmojiKeyboardViewDataSource
- (void)emojiKeyBoardView:(AGEmojiKeyboardView *)emojiKeyBoardView didUseEmoji:(NSString *)emoji {
	NSString * str = @"";
	if(mvm.mstr_text.length) {
		str = mvm.mstr_text;
	}
	str = [str stringByAppendingString:emoji];
		//调用此方法更新ui
	[self updateText:str];
	
}

	//退格
- (void)emojiKeyBoardViewDidPressBackSpace:(AGEmojiKeyboardView *)emojiKeyBoardView {
	if(mvm.mstr_text.length>0) {
		
		NSString * str = mvm.mstr_text;
			//遍历字符串中的每个字符
		NSRange fullRange = NSMakeRange(0, [mvm.mstr_text length]);
		__block NSRange lastCharacterRange = NSMakeRange(0, 0);
		[str enumerateSubstringsInRange:fullRange
								options:NSStringEnumerationByComposedCharacterSequences|NSStringEnumerationReverse
							 usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
			lastCharacterRange = substringRange;
			*stop = YES;
				//			NSLog(@"%@ %@ %@", substring, NSStringFromRange(substringRange),NSStringFromRange(enclosingRange));
		}];
		str = [mvm.mstr_text stringByReplacingCharactersInRange:lastCharacterRange withString:@""];
		[self updateText:str];
		
	}
}

- (UIColor *)randomColor {
	return [UIColor colorWithRed:drand48()
						   green:drand48()
							blue:drand48()
						   alpha:drand48()];
}

- (UIImage *)randomImage {
	CGSize size = CGSizeMake(30, 10);
	UIGraphicsBeginImageContextWithOptions(size , NO, 0);
	
	CGContextRef context = UIGraphicsGetCurrentContext();
	UIColor *fillColor = [self randomColor];
	CGContextSetFillColorWithColor(context, [fillColor CGColor]);
	CGRect rect = CGRectMake(0, 0, size.width, size.height);
	CGContextFillRect(context, rect);
	
	fillColor = [self randomColor];
	CGContextSetFillColorWithColor(context, [fillColor CGColor]);
	CGFloat xxx = 3;
	rect = CGRectMake(xxx, xxx, size.width - 2 * xxx, size.height - 2 * xxx);
	CGContextFillRect(context, rect);
	
	UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return img;
}

	//Emoji的分段图标
- (UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category {
	switch (category) {
		case AGEmojiKeyboardViewCategoryImageRecent:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"History.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageFace:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Smile.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageBell:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Food.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageFlower:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Animal.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageCar:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Building.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageCharacters:
		default:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Sign.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
	}
}

- (UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForNonSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category {
	switch (category) {
		case AGEmojiKeyboardViewCategoryImageRecent:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"History.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageFace:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Smile.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageBell:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Food.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageFlower:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Animal.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageCar:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Building.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
		case AGEmojiKeyboardViewCategoryImageCharacters:
		default:{
			UIImage *img = [JsBundleManager iconInBundleNamed:@"Sign.png" inDir:@"Emoji/EmojiCategory"];
			return img;
		}
	}
}

- (UIImage *)backSpaceButtonImageForEmojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView {
	UIImage *img = [JsBundleManager iconInBundleNamed:@"Backspace.png" inDir:@"Emoji/EmojiCategory"];
	return img;
}

- (AGEmojiKeyboardViewCategoryImage)defaultCategoryForEmojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView {
	return AGEmojiKeyboardViewCategoryImageFace;
}

#pragma mark JsVoiceInputView
- (void)jsVoiceInputView:(JsVoiceInputView *)view getText:(NSString *)text {
	NSString * str = @"";
	if(mvm.mstr_text.length) {
		str = mvm.mstr_text;
	}
	str = [str stringByAppendingString:text];
		//调用此方法更新ui
	[self updateText:str];
}

#pragma mark UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
		//	NSLog(@"textViewDidBeginEditing");
	[self updateUi];
}

/**
 该代理方法发生在text显示之前.
 text先调用该方法,然后显示.
 */
- (void)textViewDidChange:(UITextView *)textView {
		//	NSLog(@"textViewDidChange");
	NSString * text = textView.text;
	[self updateText:text];
}

- (void)updateText:(NSString *)text {
	if(text.length) {
		mlb_palceHolder.hidden = YES;
	}
	else {
		mlb_palceHolder.hidden = NO;
	}
		//每次文本内容的改变,将重新定义整个的布局需要重新计算.
	mvm.mstr_text = text;
	[self updateUi];
}

/**
 手动更新文本,需要设置vm和mtv;
 */
- (void)setText:(NSString *)text {
	[self updateText:text];
	mtv.text = text;
}


@end
